class WSManager {
    constructor(url) {
        this.socket = null
        this.reconnectAttempts = 0
        this.maxReconnect = 5
        this.init(url)
    }

    init(url) {
        this.socket = new WebSocket(url)

        this.socket.onopen = () => {
            this.reconnectAttempts = 0
            console.log('WebSocket连接已建立')
        }

        this.socket.onclose = (e) => {
            if (e.code !== 1000 && this.reconnectAttempts < this.maxReconnect) {
                setTimeout(() => this.reinit(url), 2000)
                this.reconnectAttempts++
                console.error('WebSocket连接关闭，尝试重连...')
            }
        }
    }

    reinit(url) {
        this.init(url)
    }

    onMessage(callback) {
        this.socket.onmessage = callback
    }
}

export default WSManager